<?php
/**
 * 抽奖定时任务
 * 作者：刘单风
 * 最后修改时间：2018-11-23
 * 版权：医库PHP小组
 */

/**
 * 链接数据库
 * @return mysqli
 */
function connect_db()
{
    $mysqli = new mysqli('rm-m5ezj4pb75vs6xk5v.mysql.rds.aliyuncs.com', 'ldfmedicool', 'MediCool_ldf', 'luck_prize');
    if ($mysqli->connect_error) {
        die(date('Y-m-d H:i:s').'  Connect Error: ' . $mysqli->connect_error."\r\n");
    }
    $mysqli->query("set names 'utf8'");
    return $mysqli;
}

/**
 * 开奖
 */
function openprize($mysqli)
{
    //查出所有未开奖的奖品
    $notopensql = "SELECT * FROM luck_prizes WHERE is_open=0";
    $openprizes = $mysqli->query($notopensql);
    if ($openprizes->num_rows > 0) {
        // 输出数据
        while ($prize = $openprizes->fetch_assoc()) {
            $nowtime=strtotime(date('Y-m-d H:i'));
            if (empty($prize['full_num'])) {
                //按照时间开奖
                if($prize['open_time']==$nowtime){
                    //开奖
                    opendata($mysqli,$prize['prize_type'],$prize['id'],$prize['prize_num']);
                }
            } else {
                //按照人数开奖
                //查看是否到七天了,如果到了,人数没到也要开奖
                $deadline=strtotime("+1week",$prize['publish_time']);
                $deadline=$deadline-600;
                if($deadline==$nowtime){
                    //开奖
                    opendata($mysqli,$prize['prize_type'],$prize['id'],$prize['prize_num']);
                }
            }

        }
    }
}

/**
 * 开奖处理
 */
function opendata($mysqli,$prizetype,$prizeid,$prizenum)
{
    $ids = "";
    if ($prizetype == 0) {
        //普通抽奖

        //查看今天为止15天内中奖的人,过滤掉这些人
        $endtime=time();
        $startime=strtotime("-15 day",$endtime);
        $outidsql="SELECT user_id FROM luck_join WHERE join_time>=$startime AND join_time<=$endtime AND is_win in(1,2) GROUP BY user_id";
        $outids = $mysqli->query($outidsql);
        $winneroutids=0;
        if ($outids->num_rows > 0) {
            while ($owinner = $outids->fetch_assoc()) {
                $winneroutids .= $owinner['user_id'] . ",";
            }
        }
        $winneroutids = trim($winneroutids, ",");

        //中奖人id
        $winneridsql = "SELECT SUM(index_num) AS index_num,user_id FROM luck_index WHERE prize_id=$prizeid AND user_id NOT IN ($winneroutids) GROUP BY user_id ORDER BY index_num DESC limit $prizenum";
        $winnerids = $mysqli->query($winneridsql);
        if ($winnerids->num_rows > 0) {
            while ($winner = $winnerids->fetch_assoc()) {
                $ids .= $winner['user_id'] . ",";
            }
        }
    } else {
        //组团
        //获取参与人数
        $joinsql="SELECT COUNT(*) AS joincount FROM luck_join WHERE prize_id=$prizeid";
        $joincount = $mysqli->query($joinsql);
        if ($joincount->num_rows > 0) {
            $joincount = $joincount->fetch_assoc();
            $joincount = $joincount['joincount'];
        }

        //中奖人
        if($joincount){
            $rand = mt_rand(0, $joincount - 1);
        }else{
            $rand=0;
        }
        $winneridsql="SELECT user_id FROM luck_join WHERE prize_id=$prizeid LIMIT $rand,1";
        $winnerid = $mysqli->query($winneridsql);
        if ($winnerid->num_rows > 0) {
            $winnerid = $winnerid->fetch_assoc();
            $winnerid = $winnerid['user_id'];
        }else{
            $winnerid=0;
        }
        //查看当前中奖人有没有组队
        $winnteamsql="SELECT captain_id FROM luck_team WHERE prize_id=$prizeid AND user_id=".$winnerid;
        $winnteam = $mysqli->query($winnteamsql);
        if ($winnteam->num_rows > 0) {
            $winnteam = $winnteam->fetch_assoc();
            $winnteam = $winnteam['captain_id'];
        }else{
            //说明没有组队
            $winnteam=0;
        }

        if($winnteam){
            //组队了
            //获取中奖组员
            $winneridsql = "SELECT user_id FROM luck_team WHERE prize_id=$prizeid AND captain_id=$winnteam";
            $winnerids = $mysqli->query($winneridsql);
            if ($winnerids->num_rows > 0) {
                while ($winner = $winnerids->fetch_assoc()) {
                    $ids .= $winner['user_id'] . ",";
                }
            }
            //设置运气爆棚人
            $baosql = "UPDATE luck_join SET is_luckiest=1 WHERE prize_id=$prizeid AND user_id=$winnerid";
            $mysqli->query($baosql);
        }else{
            $ids=$winnerid;
        }
    }
    $ids = trim($ids, ",");
    //将该奖品改为已开奖
    $setopensql = "UPDATE luck_prizes SET open_time=" . time() . ",is_open=1 WHERE id=$prizeid";
    $mysqli->query($setopensql);

    //将中奖人设置为已中奖
    $setwinnersql = "UPDATE luck_join SET is_win=1 WHERE user_id in ($ids) AND prize_id=$prizeid";
    $mysqli->query($setwinnersql);

    //给所有参与推送模板消息
    $joinidsql = "SELECT user_id FROM luck_join WHERE prize_id=$prizeid";
    $joinids = $mysqli->query($joinidsql);
    $join_ids="";
    if ($joinids->num_rows > 0) {
        while ($winner = $joinids->fetch_assoc()) {
            $join_ids .= $winner['user_id'] . ",";
        }
    }
    $formAction = 'https://luckprize.meditool.cn/api/prize/sendtempmsg';
    $postVals = array(
        'winnerids'=>$join_ids,
        'prizeid'=>$prizeid
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $formAction);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ($postVals));
    $res = curl_exec($ch);
    curl_close($ch);
}

// 主程序
$mysqli = connect_db();
openprize($mysqli);
$mysqli->close();